'''
@author：fc
@date：  2021/11/9
@contact：675435108@qq.com
'''
import json
import os
import numpy as np
import matplotlib.pyplot as plt

"""
文件内容&功能简要：
# 社会群体的兴趣度会随时间变化而变化
计算步骤：
以月为单位，计算每个月所有用户大打分数除以该月的用户总数
"""


class Demo:
    def __init__(self, filePath):
        self.dataPath = filePath

    def showGroup(self):
        groupRate = dict()
        if os.path.exists("json/groupRate.json"):
            groupRate = json.load(open("json/groupRate.json"))
            print("groupRate Load Ok ！")
        else:
            for file in os.listdir(self.dataPath):
                onePath = "{}/{}".format(self.dataPath, file)
                print(onePath)
                for line in open(onePath, "r").readlines():
                    if not line.strip().endswith(":"):
                        _, rate, date = line.strip().split(",")
                        newDate = "".join(date.split("-")[:2])
                        groupRate.setdefault(newDate, []).append(
                            int(rate))  # 有个疑问，每次遇到相同日期时竟不会重新赋值，他应该是如果key存在就添加，不存在就赋值
            for date in groupRate.keys():
                groupRate[date] = round(sum(groupRate[date]) / len(groupRate[date]), 2)  # 四舍五入，保留两位有线数字
            json.dump(groupRate, open("json/groupRate.json", "w"))
            print("groupRate Message Saved Ok !")
        return groupRate

    def showFigure(self, _dict, label):
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        new_dict = sorted(_dict.items(), key=lambda x: x[0], reverse=False)
        x = [one[0] for one in new_dict]
        y = [one[1] for one in new_dict]
        plt.plot(x, y, marker='o', label=label)
        plt.xticks(np.arange(len(x), step=2), rotation=90)
        plt.xlabel(u"时间-单位/月")
        plt.ylabel(u"平均打分/月")
        plt.title(u"平均评分随时间变化")
        plt.legend()  # 给图上标签说明
        plt.show()


if __name__ == '__main__':
    filePath = "./data/netflix/training_set"
    demo = Demo(filePath)
    groupRate = demo.showGroup()
    print(groupRate)
    demo.showFigure(groupRate, None)
